package com.xiaohe66.web.application.birth.convert;

import com.xiaohe66.common.util.time.ChineseDate;
import com.xiaohe66.common.util.time.LocalDateUtils;
import com.xiaohe66.web.application.birth.bo.BirthdaySaveBo;
import com.xiaohe66.web.application.birth.result.BirthdayResult;
import com.xiaohe66.web.domain.account.value.AccountId;
import com.xiaohe66.web.domain.birth.agg.Birthday;
import com.xiaohe66.web.domain.birth.value.BirthdayId;
import com.xiaohe66.web.domain.birth.value.BirthdayType;
import com.xiaohe66.web.domain.birth.value.BirthdayValue;
import com.xiaohe66.web.infrastructure.domain.adapter.birth.BirthdayConverter;
import org.mapstruct.AfterMapping;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.MappingTarget;

import java.time.LocalDate;
import java.util.List;

/**
 * @author xiaohe
 * @since 2023.07.13 11:59
 */
@Mapper
public interface BirthdayBoConverter extends BirthdayConverter {

    @Mapping(target = "id" , source = "birthdayId")
    Birthday toAgg(BirthdaySaveBo bo, BirthdayId birthdayId, AccountId createId);

    BirthdayResult toResult(Birthday agg);

    List<BirthdayResult> toResult(List<Birthday> list);

    @AfterMapping
    default void fillBirthdayName(@MappingTarget BirthdayResult result, Birthday birthday) {

        if (birthday.getBirthType() == BirthdayType.CHINESE) {

            // NOTE : 选择2019是因为没有2019没有润月
            int year = birthday.getYear() == null ? 2019 : birthday.getYear().getValue();
            ChineseDate chineseDate = ChineseDate.of(year, birthday.getMonth().getValue(), birthday.getDay().getValue());

            if (birthday.getYear() != null) {
                result.setYearName(chineseDate.getYearName());
            }

            result.setMonthName(chineseDate.getMonthName());
            result.setDayName(chineseDate.getDayName());

        } else {

            if (birthday.getYear() != null) {
                result.setYearName(birthday.getYear().getValue() + "年");
            }
            result.setMonthName(birthday.getMonth().getValue() + "月");
            result.setDayName(birthday.getDay().getValue() + "日");
        }

        BirthdayValue birthdayValue = new BirthdayValue(birthday.getBirthType(), birthday.getMonth(), birthday.getDay());
        LocalDate nextBirthdayDate = birthdayValue.nextBirthday().toDate();

        result.setNextBirthday(nextBirthdayDate.toString());

        int days = LocalDateUtils.getDays(LocalDate.now(), nextBirthdayDate);
        result.setNextBirthdayDay(days);

        if(birthday.getYear() == null){
            result.setYear(null);
        }
    }
}
